<?php

namespace app\api\controller;

use app\admin\model\DormitoryDorm;
use app\admin\model\DormitoryDormBed;
use app\common\controller\Api;
use app\common\model\BehaviorRecordDetail;
use think\Db;

/**
 * 床位接口
 */
class Bed extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (联动搜索 床位列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/27 09:31)
     * @ApiSummary  (默认只取闲置床位)
     * @ApiBody     ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/bed/cxSelect)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="dorm_id", type="int", required=true, description="寝室id", sample="")
     * @ApiParams   (name="status", type="int", required=false, description="状态 0所有 1闲置床位(默认) 2在用 ", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function cxSelect()
    {
        $dorm_id = $this->request->request('dorm_id');
        $status = $this->request->request('status', 1);

        $result = DormitoryDorm::alias('dorm')
            ->join('__DORMITORY_DORM_BED__ bed', 'dorm.number = bed.dorm_number and dorm.garden_number = bed.garden_number and dorm.building_number = bed.building_number')
            ->where(function ($query) use ($dorm_id, $status) {
                $query->where('dorm.id', $dorm_id);
                if ($status) {
                    $query->where('bed.status', $status);
                }
            })
            ->where('dorm.status', DormitoryDorm::NORMAL)
            ->field('bed.id,bed.number name,bed.num,bed.status')
            ->select();

        $this->success('', $result);
    }

    /**
     * @ApiTitle    (绑定床位)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/27 09:31)
     * @ApiSummary  ()
     * @ApiBody     ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/bed/bind)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="bed_id", type="int", required=true, description="床位", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function bind()
    {
        $bed_id = $this->request->request('bed_id');

        $bed = DormitoryDormBed::get($bed_id);

        if (!$bed) $this->error('您选择的床位不存在');

        if ($bed['status'] != '1') $this->error('您选择的床位已经被占用');

        $dorm = DormitoryDorm::where('number', $bed['dorm_number'])
            ->where('garden_number', $bed['garden_number'])
            ->where('building_number', $bed['building_number'])
            ->field('type')
            ->find();

        if (!$dorm) $this->error('您选择的寝室不存在');

        if ($dorm['type'] != $this->auth->gender) $this->error('您选择的寝室类型不正确');

        if ($this->auth->target_type == '1') {

            $count = DormitoryDormBed::where('student_id', $this->auth->target_id)->count();

            if ($count) $this->error('您已经绑定过床位了');

            // 启动事务
            Db::startTrans();
            try {

                $bed->student_id = $this->auth->target_id;
                $bed->status = 2;
                $bed->save();

                \app\admin\model\Student::where('id', $this->auth->target_id)->update(['is_bed' => 1]);

                DormitoryDorm::where('number', $bed['dorm_number'])
                    ->where('garden_number', $bed['garden_number'])
                    ->where('building_number', $bed['building_number'])
                    ->setInc('bed_used_count', 1);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage() ? $e->getMessage() : __('保存失败'));
            }


            $this->success();
        }

        $this->error();

    }

}
